package
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	import spark.components.Label;

	/**
	 * 根据AS3 Sorcerer导出的代码txt，生成对应as文件
	 */
	public class As3Sorcerer
	{
		private static var _ins:As3Sorcerer;
		
		public var printMsg:Label;
		public var exportUrl:String;
		public var importRoot:String;
		
		private var _cfgStream:FileStream;
		
		public static function get ins():As3Sorcerer
		{
			if(!_ins){
				_ins = new As3Sorcerer();
			}
			return _ins;
		}
		
		public function As3Sorcerer()
		{
		}
		public function outFiles(content:String):void
		{
			var START:String = "//-----------------------";
			var END:String = "//package ";
			var index:int = content.indexOf(START);
			var index2:int;
			var index3:int;
			while(index != -1){
				index2 = content.indexOf(START, index + 10);
				
				if(index2 == -1){
					index2 = content.length;
				}
				else{
					index2 -= 1;
				}
				
				var txt:String = content.substring(index+10, index2);
				outSingle(txt);
				
				index = content.indexOf(START, index2);
				
			}
			printMsg.text = "转换完成！";
		}
		private function outSingle(txt:String):void
		{
			var index1:int = txt.indexOf("//");
			var index2:int = txt.indexOf("\n", index1 + 1);
			var path:String = txt.substring(index1 + 2, index2-1);
			path = path.replace(/\./gi, "\/");
			path = "src/" + path;
			path += ".as";
			
			if(txt.indexOf("NetImage") != -1){
				trace(txt);
			}
			
			index2 = txt.indexOf("package ");
			var str:String = txt.substring(index2);
			
			var rootFile:File = new File(exportUrl);
			var fl:File = rootFile.resolvePath(path);
			try
			{
				printMsg.text = "正在转换：   url=" + path;
				
				_cfgStream = new FileStream();
				_cfgStream.open(fl, FileMode.WRITE);
				_cfgStream.writeUTFBytes(str);
				_cfgStream.close();
			}
			catch(e:Error)
			{
				throw new Error(e.getStackTrace());
			}
		}
	}
}